# select testFormNumber as '委托单号',sampleModel as '样品型号',sampleNumber as '样品编号',testFormItemName as '委托项名称',
# equipmentName as '设备名称',equipmentNumber as '设备编号',equipmentTWName as '设备台位名称',testCondition as '检测条件',
# varStr1 as '电流',varStr3 as '排气压力',varStr5 as '吸气压力',varStr7 as '排气温度',varStr9 as '吸气温度',varStr11 as '壳体温度',varStr13 as '频率'
# from actualtestvalueg3 where equipmentNumber = 'TA2211080005160024010101' and testFormNumber = 'ST2024099386' and sampleNumber = '2409060741K';

# 构造 SQL 查询
def construct_sql(tbl, cons, fields):
    # 构造 SELECT 部分
    select_part = ", ".join(fields)
    
    # 构造 WHERE 条件
    conditions = []
    for key, value in cons.items():
        conditions.append(f"{key} = '{value}'")
    
    # 拼接 SQL 查询
    sql = f"SELECT {select_part} FROM {tbl} WHERE {' AND '.join(conditions)};"
    return sql

# 示例表名
tbl = 'actualtestvalueg3'

# 示例查询条件
cons = {
    'testFormNumber': 'ST2024099386',
    'sampleNumber': '2409060741K',
    'equipmentNumber': 'TA2211080005160024010101'
}

# 示例字段列表
fields = [
    "testFormNumber as '委托单号'",
    "sampleModel as '样品型号'",
    "sampleNumber as '样品编号'",
    "testFormItemName as '委托项名称'",
    "equipmentName as '设备名称'",
    "equipmentNumber as '设备编号'",
    "equipmentTWName as '设备台位名称'",
    "testCondition as '检测条件'",
    "varStr1 as '电流'",
    "varStr3 as '排气压力'",
    "varStr5 as '吸气压力'",
    "varStr7 as '排气温度'",
    "varStr9 as '吸气温度'",
    "varStr11 as '壳体温度'",
    "varStr13 as '频率'"
]

# 调用函数并打印结果
sql_query = construct_sql(tbl, cons, fields)
print(sql_query)

# 将字符串写入到当前目录的 sql_query.txt 文件并换行
import os
current_directory = os.path.dirname(os.path.abspath(__file__))
file_path = os.path.join(current_directory, 'sql_query.txt')

with open(file_path, 'a') as file:
    file.write(sql_query + '\n')

print("字符串已成功写入到 sql_query.txt 文件中")